package sng.modules.view.components.city.logic
{
	import caurina.transitions.Tweener;
	
	import de.polygonal.ds.Array2;
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	import sng.data.info.BuildingInfo;
	import sng.data.info.GlobalInfo;
	import sng.data.info.GlobalTimer;
	import sng.modules.model.vo.BuildingVO;
	import sng.modules.model.vo.HudVO;
	import sng.modules.model.vo.UserBuildingVO;
	import sng.modules.view.CityMediator;
	import sng.modules.view.components.city.logic.building.BuildingCreator;
	import sng.modules.view.components.city.logic.unit.BaseBuilding;
	import sng.modules.view.components.city.logic.unit.Bonus;
	import sng.modules.view.components.city.logic.unit.BuildingQueueManager;
	import sng.modules.view.components.city.logic.unit.DragManager;
	import sng.modules.view.components.city.logic.unit.MoveCharManager;
	import sng.modules.view.components.city.logic.unit.RoadManager;
	import sng.modules.view.components.city.logic.unit.Tile;
	import sng.modules.view.components.city.state.CityNormalState;
	import sng.modules.view.components.city.state.ICityState;
	import sng.utils.BuildingUtil;

	
	public class City extends Sprite
	{
		public static const GRID_CELLSIZE:Number 	= 16;//格子的高度尺寸，该格子用于放置美术资源的最小单位
		
		public static const GRID_WIDTH:Number 	= 50;//地图宽度
		public static const GRID_LENGTH:Number 	= 50;//地图长度	
		public static const HEIGHT_NORMAL:Number 	= 3;//建筑的默认高度	
		public static const HEIGHT_TOP:Number 	= 100;//建筑的置顶高度
		//用于显示当前操作的鼠标跟随，如播种、建造、移动等等
		public static var mouseCursorContainer:Sprite = new Sprite();	
				
		//扩展isoview的，用于控制城市的视野，显示并控制城市
		public var cityView:CityView;
		//用于放置，金币、货物滑动动画
		public var attachmentContainer:Sprite = new Sprite();
		//用于放置悬浮框
		public var tipContainer:Sprite = new Sprite();
		
		public var hudVo:HudVO;
		public var mediator:CityMediator;
		
		private var cityCols:uint = 40;
		private var cityRows:uint = 40;
		private var buildingCreator:BuildingCreator = new BuildingCreator();
		
		/**
		 * 存放地图建筑类型信息
		 */		
		public static var buildingTypeArray:Array2;
		/**
		 * 用于存储iso格子上对应的建筑id信息，便于getChildById获取BaseBuilding
		 */		
		public static var buildingIdArray:Array2;
		//	buildingArray roadArray 的x/y offset补偿值，用于扩地使用
		public static var arrayOffsetX:uint = 0;
		public static var arrayOffsetY:uint = 0;
		//private var tempBuilding:BaseBuilding;
		
		/**
		 * 
		 * @param cols 地图行数
		 * @param rows 地图列数
		 * @param bArray 用户建筑列表
		 * 
		 */
		
		/**
		 * 专门用于管理城市中移动的物体。 royjin 20110706
		 */
		public var moveCharManager:MoveCharManager;
		/**
		 * 专门用于管理城市中的道路。 royjin 20110711
		 */
		public var roadManager:RoadManager;
		/**
		 * 专门用于管理采集队列。 royjin 20110713
		 */
		public var buildingQueueManager:BuildingQueueManager;
		/**
		 * 专门用于管理拾取连击奖励。 royjin 20110714
		 */
		public var bonus:Bonus;
		
		public function City(cols:uint, rows:uint,bArray:Array2, _mediator:CityMediator=null)
		{
			
			buildingTypeArray=bArray;
			cityCols = cols;
			cityRows = rows;
			mediator = _mediator
			currentState=new CityNormalState(this);//默认城市为正常操作状态
			this.addEventListener(Event.ADDED_TO_STAGE, init);
			// 合并到GroundScene中的onCityEnterFrame监听
			//eason 20110714
//			this.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
		}
		// 合并到GroundScene中的onCityEnterFrame监听
		//eason 20110714
//		protected function mouseMoveHandler(event:MouseEvent):void
//		{
//			mouseCursorContainer.x = mouseX;
//			mouseCursorContainer.y = mouseY;
//		}
		
		private function init(e:Event = null):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			createCityView();
			this.stage.addEventListener(Event.RESIZE,resizeHandler);
			GlobalTimer.Start();
//			createObjects();
			//创建道路管理类 royjin 20110706
			this.createRoadManager();
			//创建采集队列管理类 royjin 20110713
			this.createBuildingQueueManager();
		}
		
		private function createCityView():void
		{
			
			cityView = new CityView(this, 955, 600, cityCols, cityRows, GRID_CELLSIZE);
			//cityView.debugMode = true;

			cityView.panTo(0, 400);
			
			addChild(cityView);

			addChild(attachmentContainer);
			
			addChild(tipContainer);
			
			addChild(mouseCursorContainer);
			
			//初始化鼠标指针 eason 20110714
			cityView.initCityCursor(mouseCursorContainer);
			//创建拾取连击奖励类 royjin 20110714
			this.createBonus();
			
		}
		
		public function setCityState(cityState:ICityState):void
		{
			currentState=cityState;
		}
		/**
		 *当前城市的状态
		 */		
		private var _currentState:ICityState;
		
		
		public function get currentState():ICityState
		{
			return _currentState;
		}
		
		public function set currentState(value:ICityState):void
		{
			_currentState = value;
		}
		
		/**
		 *保存当前操作的物体  
		 */		
		private var _currentBuilding:BaseBuilding;
		public function get currentBuilding():BaseBuilding
		{
			return _currentBuilding;
		}
				
		public function set currentBuilding(value:BaseBuilding):void
		{
			_currentBuilding = value;

		}

		
		private function createObjects():void
		{
//			var house:BaseBuilding = new House("assets/b11.swf");
//			cityView.addTile(house, 20, 20);
//			buildingCreator.addBuilding(BuildingCreator.HOUSE, cityView, 10, 5, "assets/b11.swf");
		}
		
		private function onBuildingStartDrag(e:Event):void
		{
//			DragManager.getInstance().drag(tempBuilding, cityView);
		}

		/**
		 * 
		 * @param _building
		 * 新建建筑物 
		 * 
		 */		
		public function createBuilding(_building:UserBuildingVO):void
		{
			var vo:BuildingVO = BuildingInfo.getBuildingVOFromTemplateId(_building.templateId);
			var buildingHeight:uint = vo.buildingTypeId==BuildingUtil.ROAD_TYPE?0:HEIGHT_NORMAL;
			BaseBuilding.bId++;
			_building.buildingid = BaseBuilding.bId;
			currentBuilding = buildingCreator.addBuilding(_building, cityView, _building.x, _building.y,this);
			currentBuilding.setSize(vo.rows, vo.cols, buildingHeight);
			
			/**
			 * 整合到IsoUtil的updateAllMapDataInfo方法中
			 * 在GroundScene的addTile时会调用
			 * eason 20110715
			 */
//			//更新道路信息
////			setCityBuildData();
//			//如果是道路,需要管理 royjin 20110711
//			if(currentBuilding.IsRoad()==true)
//			{
//				this.roadManager.AddRoad(currentBuilding);
//			}
				
		}
		
		
		/**
		 *创建用户城市 leonliu
		 * 
		 */		
		public function createCity(_hudVo:HudVO):void
		{
			hudVo = _hudVo;
			cityView.groundScene.removeAllTile();
			cityView.groundScene.initBuildingInfoGridArr();
			initCityBuildData();
			var _building:BuildingVO;
			var _tempBuilding:BaseBuilding;
			var vo:BuildingVO;
			for(var i:int=0;i<hudVo.userbuildinglist.length;i++)
			{
				var _userBuildingVO:UserBuildingVO=hudVo.userbuildinglist[i] as UserBuildingVO;
//				_building=hudvo.buildinglist.getItemAt(0) as BuildingVO;//此处为临时方式，要加上按buildingID查找功能
				vo = BuildingInfo.getBuildingVOFromTemplateId(_userBuildingVO.templateId);
				var buildingHeight:uint = vo.buildingTypeId==BuildingUtil.ROAD_TYPE?0:HEIGHT_NORMAL;
				BaseBuilding.bId = _userBuildingVO.buildingid;
				_tempBuilding = buildingCreator.addBuilding(_userBuildingVO, cityView, _userBuildingVO.x, _userBuildingVO.y,this);
				_tempBuilding.setSize(vo.rows, vo.cols, buildingHeight);
				
				/**
				 * 整合到IsoUtil的updateAllMapDataInfo方法中
				 * 在GroundScene的addTile时会调用
				 * eason 20110715
				 */
////				//如果是道路,需要管理 royjin 20110711
//				if(_tempBuilding.IsRoad()==true)
//				{
//					this.roadManager.AddRoad(_tempBuilding);
//				}
			}
			/**
			 * 改为单个调用IsoUtil的updateAllMapDataInfo方法
			 * eason 20110715
			 */
//			setCityBuildData();
			//setCityIdelBuilds();
			
			//创建自由移动物体对象 royjin 20110706
			createMoveCharManager();
		}
		/**
		*创建自动移动小人逻辑
		*
		*/
		private function createMoveCharManager():void
		{
			this.moveCharManager = new MoveCharManager(this);
		}
		/**
		 *删除自动移动小人逻辑
		 *
		 */
		private function delMoveCharManager():void
		{
			if(this.moveCharManager!=null)
			{
				this.moveCharManager.dispose();
			}
		}
		/**
		 *创建道路管理类
		 *
		 */
		private function createRoadManager():void
		{
			this.roadManager = new RoadManager(this);
		}
		/**
		 *删除道路管理类
		 *
		 */
		private function delRoadManager():void
		{
			if(this.roadManager!=null)
			{
				this.roadManager.dispose();
			}
		}
		/**
		 *创建拾取连击奖励类
		 *
		 */
		private function createBonus():void
		{
			this.bonus = new Bonus();
			this.bonus.x = 580;
			this.bonus.y = 60;
			this.addChild(this.bonus);
		}
		/**
		 *删除道路管理类
		 *
		 */
		private function delBonus():void
		{
			if(this.bonus!=null)
			{
				this.removeChild(this.bonus);
				this.bonus.dispose();
			}
		}
		
		/**
		 *创建采集队列管理类
		 *
		 */
		private function createBuildingQueueManager():void
		{
			this.buildingQueueManager = new BuildingQueueManager();
		}
		/**
		 *删除采集队列管理类
		 *
		 */
		private function delBuildingQueueManager():void
		{
			if(this.buildingQueueManager!=null)
			{
				this.buildingQueueManager.dispose();
			}
		}
		
		/**
		 * 初始化城市地图信息，包括buildingTypeArray 和 buildingIdArray
		 * eason 20110715
		 */
		
		private function initCityBuildData():void
		{
			var _building:BuildingVO;
			var _userBuildingVO:UserBuildingVO;
			var vo:BuildingVO;
			
			buildingTypeArray = new Array2(GRID_WIDTH, GRID_LENGTH);
			buildingTypeArray.fill(0);
			buildingIdArray = new Array2(GRID_WIDTH, GRID_LENGTH);
			buildingIdArray.fill(0);
			cityView.astarGrid.setAllWalkable(false);
		}
		
		
		/**
		 * 全部更改为单个添加删除
		 * 请调用IsoUtil的updateAllMapDataInfo方法
		 * eason 20110715
		 */
//		/**
//		 *设置城市地图信息，包括buildingTypeArray 和 buildingIdArray
//		 * 
//		 */		
//		public function setCityBuildData():void
//		{
//			var _building:BuildingVO;
//			var _userBuildingVO:UserBuildingVO;
//			var vo:BuildingVO;
//			
//			buildingTypeArray = new Array2(GRID_WIDTH, GRID_LENGTH);
//			buildingTypeArray.fill(0);
//			buildingIdArray = new Array2(GRID_WIDTH, GRID_LENGTH);
//			buildingIdArray.fill(0);
//			
//			//add by royjin 20110707
//			cityView.astarGrid.setAllWalkable(false);
//			for(var i:int=0;i<hudVo.userbuildinglist.length;i++)
//			{
//				_userBuildingVO=hudVo.userbuildinglist[i] as UserBuildingVO;
//				vo = BuildingInfo.getBuildingVOFromTemplateId(_userBuildingVO.templateId);
//				for(var j:int=1;j<vo.rows+1;j++)
//				{
//					for(var k:int=1;k<vo.cols+1;k++)
//					{
//						if(vo.buildingTypeId==BuildingUtil.ROAD_TYPE)
//						{
//							buildingTypeArray.set(_userBuildingVO.x-j, _userBuildingVO.y-k, 2);	
//							//add by royjin 20110707 道路的地方能走
//							cityView.astarGrid.setWalkable(_userBuildingVO.x-j, _userBuildingVO.y-k,true);							
//						}else
//							buildingTypeArray.set(_userBuildingVO.x-j, _userBuildingVO.y-k, 1);	
//						
//						//设置建筑的id数组
//						buildingIdArray.set(_userBuildingVO.x-j, _userBuildingVO.y-k, _userBuildingVO.buildingid);
//						
//					}
//				}
//			}
//			//trace(buildingIdArray.dump());
//		}
		
		public function doTextTipAnimation(attachment:MovieClip,x:Number,y:Number):void
		{
			attachment.x=x;
			attachment.y=y;
			attachmentContainer.addChild(attachment);
			//city只负责添加，删除的代码在attachment的最后一帧自删 eason 20110719
		}
		
		/**
		 * TODO 用专门的类来管理动画
		 * @param point 动画开始的位置
		 * 
		 */				
		public function doGatherAnimation(point:Point, type:String="coin", isSupply:Boolean=false):void
		{
			var attachment:MovieClip;
			var iconX:uint;
			var iconY:uint
			switch(type)
			{
				case "coin":
					attachment = new AttachmentCoin();
					iconX = GlobalInfo.coinBarX;
					iconY = GlobalInfo.coinBarY;
					break;
				case "goods":
					attachment = new AttachmentGoods();
					iconX = GlobalInfo.goodsBarX;
					iconY = GlobalInfo.goodsBarY;
					break;
				case "exp":
					attachment = new AttachmentExp();
					iconX = GlobalInfo.expBarX;
					iconY = GlobalInfo.expBarY;
					break;
			}
			attachment.gotoAndStop(attachment.totalFrames);
			attachmentContainer.addChild(attachment);
			attachment.x = point.x;
			attachment.y = point.y;
			Tweener.addTween(attachment, {x:iconX, y:iconY, _bezier:{x:250, y:200}, time:1, transition:"easeOutExpo", onComplete:onFinishTween});
			if(isSupply)
			{
				attachment.x = iconX;
				attachment.y = iconY;
				Tweener.addTween(attachment, {x:point.x, y:point.y, _bezier:{x:250, y:200}, time:1, transition:"easeOutExpo", onComplete:onFinishTween});				
			}
			
			function onFinishTween():void 
			{
				attachmentContainer.removeChild(attachment);
			}
		}
		
		/**
		 *如果在新建建筑时取消，则需要取消当前的新建操作 
		 * 
		 */		
		public function cancelCreateBuilding():void
		{
			DragManager.getInstance().stopDrag();			
		}
		
		private function resizeHandler(event:Event):void 
		{
			cityView.setSize(stage.width,stage.height);
		}
		
		//首次建造商业建筑命名
		public function setBusinessBuildingName(_vo:BuildingVO):void
		{
			
			mediator.nameBuilding(_vo, hudVo.mainvo.usernick);
		}
		
	}
}